<template>
    <div class="users_wrap">
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 主体内容区域 -->
        <el-card>
            <el-row>
                <!-- 搜索框 -->
                <el-col :span="6">
                    <el-input @clear="showAllUsers" clearable placeholder="请输入内容" v-model="searchText">
                        <el-button @click="searchUsers" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </el-col>
                <!-- 添加用户按钮 -->
                <el-col :span="4">
                    <el-button @click="showAddUserForm" class="addUserBtn" type="primary">添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 用户列表 -->
            <el-table :data="usersList" border style="width: 100%">
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <!-- 状态开关 -->
                        <el-switch @change="setUserState(scope.row.id, scope.row.mg_state)" v-model="scope.row.mg_state" active-color="#2e95fb" inactive-color="#13ce66"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-row>
                            <!-- 编辑按钮 -->
                            <el-col :span="8">                               
                                <el-button @click="showModifyUserForm(scope.row.username, scope.row.id)" size="small" type="primary" icon="el-icon-edit"></el-button>
                            </el-col>
                            <!-- 分配按钮 -->
                            <el-col :span="8">                             
                                <el-button @click="showUserRoleForm(scope.row)" size="small" type="info" icon="el-icon-user"></el-button>
                            </el-col>
                            <!-- 删除按钮 -->
                            <el-col :span="8">
                                <el-button @click="removeUser(scope.row.id)" size="small" type="danger" icon="el-icon-delete"></el-button>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="usersParams.pagenum"
            :page-sizes="[2, 4, 6, 8]" :page-size="usersParams.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>

        <!-- 添加用户对话框 -->
        <el-dialog @close="clearAddUserFormText" title="提示" :visible.sync="isShowAddUserForm" width="50%">
            <!-- 表单区域 -->
            <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="addUserForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isShowAddUserForm = false">取 消</el-button>
                <el-button type="primary" @click="submitAddUserForm">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑用户对话框 -->
        <el-dialog title="提示" :visible.sync="isShowModifyUserForm" width="50%">
            <!-- 表单区域 -->
            <el-form :model="modifyUserForm" :rules="modifyUserFormRules" ref="modifyUserFormRef" label-width="100px">
                <el-form-item label="用户名" prop="modifyUserName">
                    <el-input :disabled="true" v-model="modifyUserName"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="modifyUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="modifyUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isShowModifyUserForm = false">取 消</el-button>
                <el-button type="primary" @click="submitModifyUserForm">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配用户角色对话框 -->
        <el-dialog @close="clearSelectRoles" title="提示" :visible.sync="isShowUserRoleForm" width="50%">
            <!-- 表单区域 -->
            <div>当前用户：{{modifyUserName}}</div>
            <div>当前用户角色：{{thatUserRole}}</div>
            <span>请选择用户角色：</span>
            <!-- 角色选择器 -->
             <el-select v-model="SelectRoleID" placeholder="请选择角色">
                <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
            </el-select>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isShowUserRoleForm = false">取 消</el-button>
                <el-button type="primary" @click="submitRolesForm">确 定</el-button>
            </span>
        </el-dialog>

    </div>
    

</template>

<script>
export default {
    data() {
        // 手机验证规则
        var checkMobile = (rule, value, callback) => {
            var reg = /^[1][3,4,5,7,8][0-9]{9}$/;
            if (!reg.test(value)) return callback(new Error('手机格式错误'));
            callback();
        }
        // 邮箱验证规则
        var checkEmail = (rule, value, callback) => {
            var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
            if (!reg.test(value)) return callback(new Error('邮箱格式错误'));
            callback();
        }

        return {
            // 搜索内容
            searchText: '',
            // 存储用户列表
            usersList: [],
            // 获取用户列表的参数
            usersParams: {
                query: '',
                pagenum: 1,
                pagesize: 2
            },
            // 用户总条数
            total: 0,
            // 显示或隐藏添加用户对话框
            isShowAddUserForm: false,
            // 添加用户表单参数
            addUserForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            // 添加用户表单验证规则
            addUserFormRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ]
            },
            // 编辑用户表单参数
            modifyUserForm: {
                email: '',
                mobile: ''
            },
            // 被编辑的用户名
            modifyUserName: '',
            // 编辑用户表单验证规则
            modifyUserFormRules: {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ]
            },
            // 显示或隐藏编辑用户对话框
            isShowModifyUserForm: false,
            // 被编辑的用户ID
            modifyUserID: '',
            // 显示或隐藏分配角色对话框
            isShowUserRoleForm: false,
            // 存储角色列表
            rolesList: [],
            // 记录当前用户的角色信息
            thatUserRole: '暂未分配角色',
            // 获取当前被选中的角色ID
            SelectRoleID: '',
        }
    },
    created() {
        this.getUsersList();
    },
    methods: {
        // 获取用户列表
        async getUsersList() {
            const { data: res } = await this.$http.get('users', { params: this.usersParams });
            if (res.meta.status != 200) return this.$message.error('获取用户数据列表失败');
            this.usersList = res.data.users;
            this.total = res.data.total;
            this.usersParams.pagenum = res.data.pagenum;
        },
        // 获取改变后的显示条数
        async handleSizeChange(newSizePage) {
            this.usersParams.pagesize = newSizePage;
            this.getUsersList();
        },
        // 获取改变后的当前页码
        async handleCurrentChange(newCurrentPage) {
            this.usersParams.pagenum = newCurrentPage;
            this.getUsersList();
        },
        // 搜索用户
        async searchUsers() {
            this.usersParams.query = this.searchText;
            this.getUsersList();
        },
        // 清空搜索文本时，显示所有用户
        async showAllUsers() {
            this.usersParams.query = this.searchText;
            this.getUsersList();
        },
        // 设置用户状态
        async setUserState(userID, userState) {
            const { data: res } = await this.$http.put(`users/${userID}/state/${userState}`);
            if (res.meta.status != 200) return this.$message.error('设置用户状态失败');
            this.$message.success('设置用户状态成功');
            this.getUsersList();
        },
        // 删除用户
        async removeUser(userID) {
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then( async () => {
                const { data: res } = await this.$http.delete(`users/${userID}`);
                if (res.meta.status != 200) return this.$message.error('删除用户失败');
                this.$message.success('删除用户成功');
                this.getUsersList();
            }).catch(() => {
                this.$message.info('取消了删除用户操作');
            });
            
        },
        // 显示添加用户对话框
        showAddUserForm() {
            this.isShowAddUserForm = true;
        },
        // 对话框关闭时，清空表单数据
        clearAddUserFormText() {
            this.$refs.addUserFormRef.resetFields();
        },
        // 提交注册表单
        submitAddUserForm() {
            this.$refs.addUserFormRef.validate( async valid => {
                if (!valid) return this.$message.error('注册失败，请检查数据格式');
                const { data: res } = await this.$http.post('users', this.addUserForm);
                if (res.meta.status != 201) return this.$message.error('注册用户失败');
                this.$message.success('注册用户成功');
                this.isShowAddUserForm = false;
                this.getUsersList();
            });
        },
        // 显示编辑用户对话框
        async showModifyUserForm(userName,userID) {
            this.isShowModifyUserForm = true;
            this.modifyUserName = userName;
            this.modifyUserID = userID;
            const { data: res } = await this.$http.get(`users/${userID}`);
            if (res.meta.status != 200) return this.$message.error('查询用户信息失败');
            this.modifyUserForm.email = res.data.email;
            this.modifyUserForm.mobile = res.data.mobile;
        },
        // 提交编辑用户表单
        async submitModifyUserForm() {
            const { data: res } = await this.$http.put(`users/${this.modifyUserID}`, this.modifyUserForm);
            if (res.meta.status != 200) return this.$message.error('更新用户失败');
            this.$message.success('更新用户成功');
            this.isShowModifyUserForm = false;
            this.getUsersList();
        },
        // 显示分配角色对话框
        async showUserRoleForm(user) {
            this.isShowUserRoleForm = true;
            this.modifyUserName = user.username;
            this.modifyUserID = user.id;
            // 获取角色列表
            const { data: res } = await this.$http.get('roles');
            if (res.meta.status != 200) return this.$message.error('获取角色列表失败');
            this.rolesList = res.data;
            // 获取当前用户的角色ID
            const { data: role } = await this.$http.get(`users/${user.id}`);
            if (role.meta.status != 200) return this.$message.error('获取当前用户角色ID失败');

            // 该用户有分配角色
            if (role.data.rid != -1 && role.data.rid != 0) {
                // 获取该用户的角色信息
                const { data: user } = await this.$http.get(`roles/${role.data.rid}`);
                this.thatUserRole = user.data.roleName;
            } else {
                this.thatUserRole = role.data.rid == 0 ? '超级管理员' : '暂未分配角色';
            }
        },
        // 对话框关闭时，清空被选中的角色ID
        clearSelectRoles() {
            this.SelectRoleID = '';
        },
        // 提交分配角色表单
        async submitRolesForm() {
            // 角色ID不等于空，就提交表单
            if (this.SelectRoleID != '') {
                const { data: res } = await this.$http.put(`users/${this.modifyUserID}/role`, { rid: this.SelectRoleID});
                if (res.meta.status != 200) return this.$message.error('分配角色失败');
                this.$message.success('分配角色成功');
                this.getUsersList();
            } else {
                this.$message.info('取消了分配角色');
            }
            this.isShowUserRoleForm = false;
        }
    }
}
</script>

<style lang="less" scoped>
.addUserBtn {
    margin-left: 20px;
}
</style>